package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.LeaseHouseContentRecyclerViewAdapter;
import com.weixin.paleituo.adapter.LeaseHouseMenuRecyclerViewAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.BuildingsBean;
import com.weixin.paleituo.bean.HouseSaleStateBean;
import com.weixin.paleituo.bean.LevelsBean;
import com.weixin.paleituo.bean.OrderBean;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.bean.UnitsBean;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.CheckLeaseHouseEvent;
import com.weixin.paleituo.eventbus.CheckRoomEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.LogUtils;
import com.weixin.paleituo.util.NetUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.AlertPopuCommon;
import com.weixin.paleituo.view.LoadingPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 选择房号
 */
public class LeaseHouseActivity extends BaseActivity {
    @BindView(R.id.iv_back_layout_head)
    ImageView mIvBackLayoutHead;
    @BindView(R.id.tv_title_layout_head)
    TextView mTvTitleLayoutHead;
    @BindView(R.id.tv_small_title_layout_head)
    TextView mTvSmallTitleLayoutHead;
    @BindView(R.id.iv_arrow_layout_head)
    ImageView mIvArrowLayoutHead;
    @BindView(R.id.ll_arrowroot_layout_head)
    LinearLayout mLlArrowrootLayoutHead;
    @BindView(R.id.recycle_nume_activity_lease_house)
    RecyclerView mRecycleNumeActivityLeaseHouse;
    @BindView(R.id.recycle_content_activity_lease_house)
    RecyclerView mRecycleContentActivityLeaseHouse;
    @BindView(R.id.heheh)
    LinearLayout mHeheh;
    @BindView(R.id.tv_submit_activity_lease_house)
    TextView mTvSubmitActivityLeaseHouse;
    @BindView(R.id.ll_bottomroot_activity_lease_house)
    LinearLayout mLlBottomrootActivityLeaseHouse;

    @BindView(R.id.headroot_ativity_lease_house)
    LinearLayout mllHeadRootView;

    private List<String> mList;

    private LeaseHouseContentRecyclerViewAdapter mLeaseHouseContentRecyclerViewAdapter;


    private LoadingPager mLoadingPager;
    private String mHouseId;
    private LeaseHouseMenuRecyclerViewAdapter mLeaseHouseMenuRecyclerViewAdapter;
    private List<UnitsBean> mUnitsBeanList;
    private List<LevelsBean> mLevelsBeanList;
    private List<String> mStringList;
    private Map<String, String> mMap;
    private Dialog mLoadingDialog;

    private int checkRoomId=-1;
    private AlertPopuCommon mPopuCommon;

    @Override
    protected void initView() {
        mLoadingPager = new LoadingPager(this,Contans.HOUSE_SOLDOUT_TYPE) {
            @Override
            protected void close() {
                finish();
            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(LeaseHouseActivity.this,R.layout.activity_lease_house);
            }

            @Override
            protected void reLoading() {

                retryLoading();


            }
        };
      //  setContentView(R.layout.activity_lease_house);
        setContentView(mLoadingPager);

    }

    @Override
    protected void initData() {
        super.initData();
        EventBus.getDefault().register(this);
        mUnitsBeanList = new ArrayList<>();
        //内容
        mLevelsBeanList = new ArrayList<>();

        mStringList = new ArrayList<>();

        mMap = new HashMap<>();

        mLeaseHouseMenuRecyclerViewAdapter = new LeaseHouseMenuRecyclerViewAdapter(this, mUnitsBeanList);
        //设置布局管理器
        mRecycleNumeActivityLeaseHouse.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mRecycleNumeActivityLeaseHouse.setAdapter(mLeaseHouseMenuRecyclerViewAdapter);
        //设置Item增加、移除动画
        mRecycleNumeActivityLeaseHouse.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
        mLeaseHouseContentRecyclerViewAdapter = new LeaseHouseContentRecyclerViewAdapter(this,mLevelsBeanList);
        //设置布局管理器
        mRecycleContentActivityLeaseHouse.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mRecycleContentActivityLeaseHouse.setAdapter(mLeaseHouseContentRecyclerViewAdapter);
        //设置Item增加、移除动画
        mRecycleContentActivityLeaseHouse.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
       /* mRecyclerVieContent.addItemDecoration(new DividerItemDecoration(
                this, DividerItemDecoration.VERTICAL));*/

        retryLoading();

    }

    /**
     * 重新加载
     */
    private void retryLoading() {
        mHouseId = getIntent().getStringExtra(Contans.INTENT_DATA);
        Observable<StatusCode<HouseSaleStateBean>> houseSaleState = ApiUtils.getApi().getHouseSaleState(mHouseId);
        HttpUtil.getInstance().toSubscribe(houseSaleState, new ProgressSubscriber<HouseSaleStateBean>(this) {


            @Override
            protected void _onNext(StatusCode<HouseSaleStateBean> t) {
                HouseSaleStateBean houseSaleStateBean = t.getData();
                if (houseSaleStateBean!=null && houseSaleStateBean.getUnits()!=null &&houseSaleStateBean.getBuildings()!=null &&houseSaleStateBean.getUnits().size()>0 &&houseSaleStateBean.getBuildings().size()>0 ){

                    mLoadingPager.showPagerView(Contans.STATE_SUCCEED);
                    setDate(houseSaleStateBean);
                }else {
                    mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                }
            }

            @Override
            protected void _onError(String message) {
                if (Contans.HOUSE_SOLD_OUT.equalsIgnoreCase(message)){
                    mLoadingPager.showPagerView(Contans.STATE_SOLDOUT);

                }else {
                    mLoadingPager.showPagerView(Contans.STATE_ERROR);
                }
            }
        }, "", lifecycleSubject, false, true);
    }

    /**
     * 设置数据
     * @param houseSaleStateBean
     */
    private void setDate( HouseSaleStateBean houseSaleStateBean) {
        mStringList.clear();
        mMap.clear();
      //  mStringList.addAll(h)
        List<BuildingsBean> buildings = houseSaleStateBean.getBuildings();
        if (buildings!=null &&buildings.size()>0){
            for (BuildingsBean buildingsBean:buildings){
                mMap.put(buildingsBean.getBuilding(),buildingsBean.getBuildingId()+"");
                mStringList.add(buildingsBean.getBuilding());
            }
            mTvSmallTitleLayoutHead.setText(houseSaleStateBean.getBuildings().get(0).getBuilding()+"");
        }

        mTvSmallTitleLayoutHead.setVisibility(View.VISIBLE);

        mIvArrowLayoutHead.setVisibility(View.VISIBLE);
        mTvTitleLayoutHead.setVisibility(View.VISIBLE);
        mTvTitleLayoutHead.setText(houseSaleStateBean.getHouses()+"");

        mUnitsBeanList.clear();
        mUnitsBeanList.addAll(houseSaleStateBean.getUnits());
        mLeaseHouseMenuRecyclerViewAdapter.notifyDataSetChanged();

/*        mLeaseHouseMenuRecyclerViewAdapter = new LeaseHouseMenuRecyclerViewAdapter(this, mUnitsBeanList);
        //设置布局管理器
        mRecycleNumeActivityLeaseHouse.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mRecycleNumeActivityLeaseHouse.setAdapter(mLeaseHouseMenuRecyclerViewAdapter);
        //设置Item增加、移除动画
        mRecycleNumeActivityLeaseHouse.setItemAnimator(new DefaultItemAnimator());
        //添加分割线*/

        mLevelsBeanList.clear();
        mLevelsBeanList.addAll(houseSaleStateBean.getUnits().get(0).getLevels());
        mLeaseHouseContentRecyclerViewAdapter.notifyDataSetChanged();

     /*   mLeaseHouseContentRecyclerViewAdapter = new LeaseHouseContentRecyclerViewAdapter(this,mLevelsBeanList);
        //设置布局管理器
        mRecycleContentActivityLeaseHouse.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mRecycleContentActivityLeaseHouse.setAdapter(mLeaseHouseContentRecyclerViewAdapter);
        //设置Item增加、移除动画
        mRecycleContentActivityLeaseHouse.setItemAnimator(new DefaultItemAnimator());
        //添加分割线
       *//* mRecyclerVieContent.addItemDecoration(new DividerItemDecoration(
                this, DividerItemDecoration.VERTICAL));*/
        mLeaseHouseContentRecyclerViewAdapter.notifyDataSetChanged();
        mLeaseHouseMenuRecyclerViewAdapter.setOnItemClickListener(new LeaseHouseMenuRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onClick(View v, int position) {
               // mLevelsBeanList.
                List<LevelsBean> levels = mUnitsBeanList.get(position).getLevels();
                mLevelsBeanList.clear();
                mLevelsBeanList.addAll(levels);
                mRecycleContentActivityLeaseHouse.smoothScrollToPosition(0);
                mLeaseHouseContentRecyclerViewAdapter.notifyDataSetChanged();

                mLeaseHouseMenuRecyclerViewAdapter.setCheckPostion(position);
                mLeaseHouseMenuRecyclerViewAdapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    protected void initEvent() {
        super.initEvent();


    }

    public static void startActivity(Context context,String houseId) {
        Intent intent = new Intent(context, LeaseHouseActivity.class);
        intent.putExtra(Contans.INTENT_DATA,houseId);
        context.startActivity(intent);
    }


    @OnClick(R.id.ll_arrowroot_layout_head)
    public void onMllArrowRootLayoutHeadClicked() {

    if (mPopuCommon==null){
        mPopuCommon = new AlertPopuCommon(LeaseHouseActivity.this, Contans.DIAG_TYPE_SELECT_HOUSE, mStringList,mTvSmallTitleLayoutHead.getText().toString());

    }else {
        mPopuCommon.setChekStr(mTvSmallTitleLayoutHead.getText().toString());

    }

        mPopuCommon.showAsDropDown(mllHeadRootView);
    }

    @OnClick(R.id.tv_submit_activity_lease_house)
    public void onMTvSubmitActivityLeaseHouseClicked() {

        if (checkRoomId==-1){
            ToastUtils.makeText("请选择房号");
            return;
        }
        if (!BaseApplication.isLoginSuccess){
            ToastUtils.makeText("请先登录");
            LoginActivity.startActivity(this,true);
            return;
        }

        if (!NetUtils.NetwrokIsUseful(this)){
            ToastUtils.makeText(R.string.check_internet);

            return;
        }
        Observable<StatusCode<OrderBean>> observable = ApiUtils.getApi().createOrder(mHouseId, checkRoomId + "", BaseApplication.sUserInfoBean.userId,"1",BaseApplication.sUserInfoBean.getToken())
                .compose(RxHelper.getObservaleTransformer())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingPager == null) {

                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(LeaseHouseActivity.this, "");
                        }
                        LoadingDialogUtils.show(mLoadingDialog);

                    }
                }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderBean>(this) {

            @Override
            protected void _onNext(StatusCode<OrderBean> t) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                OrderBean orderBean = t.getData();
                if (t.isFlag()&&orderBean!=null &&orderBean.getDeposit()!=null &&orderBean.getDeposit().size()>0){
                    LogUtils.i(TAG,"提交订单获取的数据:::"+orderBean.toString()  );
                    OrdersActivity.startActivity(LeaseHouseActivity.this,orderBean, checkRoomId,1);
                    finish();
                }else {
                    ToastUtils.makeText(t.getDetailMsg()+"");
                }
            }
            @Override
            protected void _onError(String message) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);

                if (Contans.HOUSE_SOLD_OUT.equalsIgnoreCase(message)){
                    mLoadingPager.showPagerView(Contans.STATE_SOLDOUT);
                }else {
                    ToastUtils.makeText(message);
                }
            }
        },"",lifecycleSubject,false,true);


     /*     Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
              PayTask alipay = new PayTask(LeaseHouseActivity.this);
                Map<String, String> result = alipay.payV2(AliPayContant.orderInfo, true);
                Log.i("msp", result.toString());
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();*/
     // OrdersActivity.startActivity(this);
//    AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipaydev.com/gateway.do","2016072200101XXXX","请复制第1步中生成的密钥中的商户应用私钥","json","utf-8","沙箱环境RSA2支付宝公钥","RSA2");
      /* Observable oderInfo = ApiUtils.getApi().getOderInfo("91")
                .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog1==null){
                        mLoadingDialog1 = LoadingDialogUtils.createLoadingDialog(LeaseHouseActivity.this, "");

                        }
                        LoadingDialogUtils.show(mLoadingDialog);

                    }
                }).subscribeOn(AndroidSchedulers.mainThread());


        HttpUtil.getInstance()
                .toSubscribe(oderInfo, new ProgressSubscriber<String>(LeaseHouseActivity.this) {
            @Override
            protected void _onNext(final String s) {

                LogUtils.i(TAG,"订单信息  ："+s);
                LoadingDialogUtils.closeDialog(mLoadingDialog);

                Runnable payRunnable = new Runnable() {

                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(LeaseHouseActivity.this);
                        Map<String, String> result = alipay.payV2(s, true);
                        Log.i("msp", result.toString());


                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();



            }

            @Override
            protected void _onError(String message) {

                ToastUtils.makeText(message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);

            }
        },"",lifecycleSubject,false,true);*/
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void checkLeseHouseEvent(CheckLeaseHouseEvent leaseHouseEvent){

        String mbuilding = leaseHouseEvent.getMbuilding();

        String buildingId = mMap.get(mbuilding);

        //请求数据
        if (StringUtils.isEmpty(buildingId) ||mbuilding.equals(mTvSmallTitleLayoutHead.getText().toString())){
            return;
        }
        mTvSmallTitleLayoutHead.setText(leaseHouseEvent.getMbuilding());
        Observable observable = ApiUtils.getApi().getHouseUnit(buildingId).compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                if (mLoadingDialog == null) {

                    mLoadingDialog = LoadingDialogUtils.createLoadingDialog(LeaseHouseActivity.this, "");
                }
                LoadingDialogUtils.show(mLoadingDialog);

            }
        }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<UnitsBean>>(this) {


            @Override
            protected void _onNext(StatusCode<List<UnitsBean>> t) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                List<UnitsBean> uiUtils = t.getData();
                if (uiUtils!=null &&uiUtils.size()>0){
                    mLeaseHouseMenuRecyclerViewAdapter.setCheckPostion(0);


                    mUnitsBeanList.clear();
                    mUnitsBeanList.addAll(uiUtils);
                    mLeaseHouseMenuRecyclerViewAdapter.notifyDataSetChanged();


                    mLevelsBeanList.clear();
                    mLevelsBeanList.addAll(uiUtils.get(0).getLevels());
                    mLeaseHouseContentRecyclerViewAdapter.notifyDataSetChanged();

                }else {
                    mUnitsBeanList.clear();
                    mLeaseHouseMenuRecyclerViewAdapter.notifyDataSetChanged();

                    mLevelsBeanList.clear();
                    mLeaseHouseContentRecyclerViewAdapter.notifyDataSetChanged();

                }

            }

            @Override
            protected void _onError(String message) {
                mUnitsBeanList.clear();
                mLevelsBeanList.clear();
                ToastUtils.makeText(message);
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                mLeaseHouseContentRecyclerViewAdapter.notifyDataSetChanged();
                mLeaseHouseMenuRecyclerViewAdapter.notifyDataSetChanged();


            }
        },"",lifecycleSubject,false,true);





    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void checkRoomEvent(CheckRoomEvent checkRoomEvent){
        if (checkRoomId==checkRoomEvent.getRoomId()){
            //已经选中
            checkRoomId=-1;
        }else {
            checkRoomId=checkRoomEvent.getRoomId();

        }


        mLeaseHouseContentRecyclerViewAdapter.setRoomId(checkRoomId);
        mLeaseHouseContentRecyclerViewAdapter.notifyDataSetChanged();


    }

    @OnClick(R.id.iv_back_layout_head)
public void onIvBackOnCheck(){
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
